<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/30 0030
 * Time: 14:28
 */

namespace app\index\controller;
use app\index\model\Cate;
use app\index\model\Question;
use app\index\model\User;
use think\Controller;
use think\Loader;
use think\Db;

class Posted extends Controller
{
	/**
	 * 发表帖子主页
	 * @return mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function index(){
		$cate = Db::name('cate')->order('orderby desc')->select();
		$this->assign('cate',$cate);

		$this->assign('title', '发帖');
		return $this->fetch();
	}

	/**
	 * 发布帖子主页
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function addPost(){
		if (!session('user_id')){
			$this->error('请先登陆');
		}
		$post = input('post.');
		if (strlen($post['content'])<10){
			$this->error('内容太简短,可以尝试多写一点');
		}
		$validate = Loader::validate('CheckReg');
		if(!$validate->scene('captcha')->check($post)){
			$this->error($validate->getError());
		}
		$post['create_time'] = time();
		$post['user_id'] = session('user_id');
		$res = User::get(session('user_id'));
		if ($res->kiss<$post['kiss']){
			$this->error('飞吻不够，请及时充值');
		}else{
			Db::table('fly_user')->where('user_id',session('user_id'))->setDec('kiss',$post['kiss']);
		}
		$res = Question::create($post);
		if ($res){
			$this->success('发布成功',url('index/Nom/index',['qid'=>$res->question_id]));
		}else{
			$this->error('发布失败');
		}
	}

	/**
	 * 富文本编辑器上传图片方法
	 */
	public function upload(){
		$file = request()->file('file');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if($file){
				$info = $file->move(ROOT_PATH . 'public/static' . DS . 'PostedImg');
				if($info){
					$face = '/static/PostedImg/'.date('Ymd').'/'.$info->getFilename();
					$data = ['code'=>0,'msg'=>'上传成功','data'=>['src'=>$face,'title'=>'图片名称']];
					exit(json_encode($data));
			}else{
				// 上传失败获取错误信息
				$this->error('上传失败');
			}
		}
	}

}